package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @PostMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){
        //1.从redis中根据用户的手机号和RedisMessageConstant类的后缀来获得用户验证码。
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        Jedis jedis = jedisPool.getResource();
        String code = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //2.获得redis中的验证码和用户输入的验证码进行对比
        if (code == null || validateCode == null || !code.equals(validateCode)){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
        //3.判断用户的会员数据是否存在
        //4.将会员数据保存到Redis中
        memberService.check(telephone);
        //5.将用户手机号保存到客户端
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        //设置此路径可在服务器内共享
        cookie.setPath("/");
        //设置时间为1个月
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
